package com.xiaomai.center.controller;

import com.google.gson.Gson;
import com.xiaomai.center.entity.UcenterMember;
import com.xiaomai.center.service.UcenterMemberService;
import com.xiaomai.center.util.ConstantPropertiesUtil;

import com.xiaomai.center.util.HttpClientUtils;
import com.xiaomai.commonutil.JwtUtils;
import com.xiaomai.servicebase.config.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;


@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;
    //扫完微信二维码会执行这个方法
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) throws Exception {

            //1.根据获得的code请求该路径返回access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //利用httpClient访问获取结果字符串
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //把字符串转换成map以便获取其中的值 利用gson
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String)map.get("access_token");
            String openid = (String)map.get("openid");
             UcenterMember member = memberService.selectByWxID(openid);
             if (member == null) {//注册
                 //2.根据获得的access_token和openid再请求微信提供固定地址获取扫码人信息
                 String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                         "?access_token=%s" +
                         "&openid=%s";
                 String userInfoUrl = String.format(
                         baseUserInfoUrl,
                         accessToken,
                         openid
                 );
                 //模拟请求
                 String userInfo = HttpClientUtils.get(userInfoUrl);
                 //解析json
                 HashMap<String, Object> mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                 String nickname = (String) mapUserInfo.get("nickname");
                 String headimgurl = (String) mapUserInfo.get("headimgurl");

                 //3.微信扫描查询数据库是否有该微信id，无则自动注册，有则登录。
                 member = new UcenterMember();
                 member.setOpenid(openid);
                 member.setAvatar(headimgurl);
                 member.setNickname(nickname);
                 memberService.save(member);
             }
                 //使用jwt传递用户信息到其它页面，cookie不能跨域
                 String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
                 return "redirect:http://localhost:3000?token=" + jwtToken;


    }

    @GetMapping("login")
    public String genQrConnect(HttpSession session) {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对地址进行URLEncodeer编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, e.getMessage());
        }
//赋值
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        return "redirect:" + url;
    }
}
